﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.IO.IsolatedStorage;
using System.Xml.Linq;
using System.IO;
using System.Runtime.Serialization;
using System.Xml.Serialization;
using System.Collections.Generic;
using System.Linq;
using System.Collections.ObjectModel;
using System.ComponentModel;
using Microsoft.Phone;
using ProtoType.ProtoTypeService;

namespace ProtoType.DataStorage
{
    public class DataStructureStore : INotifyPropertyChanged
    {
        ProtoTypeServiceClient client = new ProtoTypeServiceClient();

        public DataStructureStore()
        {
            // Items = LoadFormList();
        }

        [XmlElement("Forms")]
        public List<Form> Forms { get; set; }

        [XmlElement("ControlsList")]
        public List<ControlDesign> ControlsList { get; set; }
        public ObservableCollection<Form> Items { get; private set; }

        public void CreateFormControl(string formid, string controName, string contolType, string controldataType)
        {
            using (IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication())
            {
                XDocument doc;
                IsolatedStorageFileStream isoStream;

                //if the records file does not exist 
                if (!isoStore.FileExists("formcontrols.xml"))
                {
                    int id = 1;
                    //create new document 
                    isoStream = new IsolatedStorageFileStream("formcontrols.xml", FileMode.Create, isoStore);
                    doc = new XDocument(new XDeclaration("1.0", "utf-8", "yes"),
                                new XElement("formdesign",
                                    new XElement("form", new XAttribute("id", formid),
                                        new XElement("control",
                                         new XAttribute("id", id.ToString()),
                                           new XElement("cname", controName),
                                            new XElement("ctype", contolType)))));
                    doc.Save(isoStream);
                    isoStream.Close();
                }
                else
                {
                    //read the current data and add a new record or modify the old one 
                    isoStream = new IsolatedStorageFileStream("formcontrols.xml", FileMode.Open, isoStore);
                    doc = XDocument.Load(isoStream);
                    isoStream.Close();
                    int id = 1;
                    var conele = from c in doc.Descendants("form") where c.Attribute("id").Value == formid select c;
                    if (conele.ToList().Count != 0)
                    {
                        XElement element = conele.ElementAt(0);
                        id = element.Elements("control").Count();
                        id = id + 1;
                        element.Add(new XElement("control",
                                         new XAttribute("id", id),
                                         new XElement("cname", controName),
                                         new XElement("ctype", contolType)
                                         ));
                    }
                    else
                    {
                        doc.Root.Add(new XElement("form", new XAttribute("id", formid),
                                 new XElement("control",
                                         new XAttribute("id", id),
                                         new XElement("cname", controName),
                                         new XElement("ctype", contolType))));
                    }
                    isoStream = new IsolatedStorageFileStream("formcontrols.xml", FileMode.Create, isoStore);
                    doc.Save(isoStream);
                    isoStream.Close();

                }
            }
        }

        public void CreateForm(string formName, string description)
        {

            using (IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication())
            {

                XDocument doc;
                IsolatedStorageFileStream isoStream;
                bool available = isoStore.FileExists("forms.xml");
                //if the records file does not exist 
                if (!isoStore.FileExists("forms.xml"))
                {
                    int id = 1;
                    //create new document 
                    isoStream = new IsolatedStorageFileStream("forms.xml", FileMode.Create, isoStore);
                    doc = new XDocument(new XDeclaration("1.0", "utf-8", "yes"),
                                new XElement("forms",
                                    new XElement("form", new XElement("id", id),
                                    new XElement("name", formName),
                                    new XElement("description", description))));


                    doc.Save(isoStream);
                    isoStream.Close();
                }
                else
                {
                    //read the current data and add a new record or modify the old one 
                    isoStream = new IsolatedStorageFileStream("forms.xml", FileMode.Open, isoStore);
                    if (isoStream.Length > 0)
                    {
                        doc = XDocument.Load(isoStream);
                        isoStream.Close();

                        int id = 0;

                        var companies = from comp in doc.Descendants("form")
                                        orderby (int)comp.Element("id") descending
                                        select comp;

                        foreach (var comp in companies)
                        {
                            id = int.Parse(comp.Element("id").Value);
                            break;
                        }
                        id = id + 1;

                        doc.Element("forms").Add(new XElement("form",
                            new XElement("id", id),
                            new XElement("name", formName),
                            new XElement("description", description)));


                        isoStream = new IsolatedStorageFileStream("forms.xml", FileMode.Create, isoStore);
                        doc.Save(isoStream);
                        isoStream.Close();
                    }

                }
            }
        }

        public ObservableCollection<XElement> LoadformControlList(string formid)
        {
            ObservableCollection<XElement> formcontrolelements = new ObservableCollection<XElement>();
            using (IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication())
            {
                IsolatedStorageFileStream stream;
                if (isoStore.FileExists("formcontrols.xml"))
                {
                    stream = new IsolatedStorageFileStream("formcontrols.xml", FileMode.Open, isoStore);
                    XElement formdoc = XElement.Load(stream);
                    stream.Close();
                    var formcontrols = from fc in formdoc.Descendants("form")
                                       where fc.Attribute("id").Value == formid
                                       select fc;
                    formcontrolelements = formcontrols.ToObservableCollection();
                }
            }
            return formcontrolelements;
        }

        public event PropertyChangedEventHandler PropertyChanged;

        private void NotifyPropertyChanged(String propertyName)
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (null != handler)
            {
                handler(this, new PropertyChangedEventArgs(propertyName));
            }
        }

        //21 sept 2010
        public ObservableCollection<XElement> LoadFormList()
        {
            ObservableCollection<XElement> formslist = new ObservableCollection<XElement>();
            using (IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication())
            {
                XDocument Xdoc;
                IsolatedStorageFileStream stream;
                if (isoStore.FileExists("forms.xml"))
                {
                    stream = new IsolatedStorageFileStream("forms.xml", FileMode.Open, isoStore);
                    Xdoc = XDocument.Load(stream);
                    stream.Close();

                    var forms = (from f in Xdoc.Root.Elements("form")
                                 select f);
                    formslist = forms.ToObservableCollection();
                }
            }
            return formslist;
        }

        public void SetformLayout(string formid, string layouttype)
        {
            using (IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication())
            {
                IsolatedStorageFileStream isoStream;
                XDocument formdoc;
                if (isoStore.FileExists("forms.xml"))
                {
                    isoStream = new IsolatedStorageFileStream("forms.xml", FileMode.Open, isoStore);
                    formdoc = XDocument.Load(isoStream);
                    isoStream.Close();

                    var forms = from form in formdoc.Descendants("form")
                                where form.Element("id").Value == formid
                                select form;
                    if (forms.Elements().Count() != 0)
                    {
                        XElement element = forms.ElementAt(0);
                        if (element.Element("layout") != null)
                        {
                            element.Elements("layout").Remove();
                        }
                        element.Add(new XElement("layout", new XAttribute("type", layouttype)));
                    }

                    isoStream = new IsolatedStorageFileStream("forms.xml", FileMode.Create, isoStore);
                    formdoc.Save(isoStream);
                    isoStream.Close();
                }
            }
        }

        public void SetformDetailLayout(string formid, string detaillayouttype)
        {

            using (IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication())
            {
                IsolatedStorageFileStream isoStream;
                if (isoStore.FileExists("forms.xml"))
                {
                    isoStream = new IsolatedStorageFileStream("forms.xml", FileMode.Open, isoStore);
                    XElement formdoc = XElement.Load(isoStream);
                    isoStream.Close();

                    var forms = from form in formdoc.Descendants("form")
                                where form.Element("id").Value == formid
                                select form;
                    if (forms.Elements().Count() != 0)
                    {
                        XElement element = forms.ElementAt(0);
                        if (element.Element("detaillayout") != null)
                        {
                            element.Elements("detaillayout").Remove();
                        }
                        element.Add(new XElement("detaillayout", new XAttribute("type", detaillayouttype)));
                    }

                    isoStream = new IsolatedStorageFileStream("forms.xml", FileMode.Create, isoStore);
                    formdoc.Save(isoStream);
                    isoStream.Close();
                }
            }
        }

        public void SaveModifiedLayout(string formId, string xamltemplate)
        {
            using (IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication())
            {
                XDocument formcontrolsdoc;
                IsolatedStorageFileStream stream;
                if (isoStore.FileExists("formcontrols.xml"))
                {
                    stream = new IsolatedStorageFileStream("formcontrols.xml", FileMode.Open, isoStore);
                    if (stream.Length > 0)
                    {
                        formcontrolsdoc = XDocument.Load(stream);
                        stream.Close();
                        //read the current data and add a new record or modify the old one
                        var formtemplate = from c in formcontrolsdoc.Descendants("form") where c.Attribute("id").Value == formId select c;
                        if (formtemplate.ToList().Count != 0)
                        {
                            XElement element = formtemplate.ElementAt(0);
                            element.Elements("Template").Remove();
                            if (xamltemplate != string.Empty)
                                element.Add(new XElement("Template", xamltemplate));
                        }
                        stream = new IsolatedStorageFileStream("formcontrols.xml", FileMode.Create, isoStore);
                        formcontrolsdoc.Save(stream);
                        stream.Close();
                    }
                }
            }
        }

        public void SetBindingelements(string formid, string tag, string Selecteditem, string cName)
        {
            using (IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication())
            {
                XDocument Xdoc;
                IsolatedStorageFileStream stream;
                if (isoStore.FileExists("forms.xml"))
                {
                    stream = new IsolatedStorageFileStream("forms.xml", FileMode.Open, isoStore);
                    Xdoc = XDocument.Load(stream);
                    stream.Close();

                    var selectedform = from form in Xdoc.Descendants("form")
                                       where form.Element("id").Value == formid
                                       select form;
                    if (selectedform.Elements().Count() != 0)
                    {
                        XElement element = selectedform.ElementAt(0);
                        string layouttype = element.Element("layout").Attribute("type").Value;

                        if (element.Element("layout").Element(tag) != null)
                        {
                            element.Element("layout").Element(tag).Element("bid").Value = Selecteditem;
                            element.Element("layout").Element(tag).Element("name").Value = cName.ToString();
                        }
                        else
                        {
                            element.Element("layout").Add(new XElement(tag,
                            new XElement("bid", Selecteditem),
                            new XElement("name", cName)));
                        }
                        stream = new IsolatedStorageFileStream("forms.xml", FileMode.Create, isoStore);
                        Xdoc.Save(stream);
                        stream.Close();
                    }
                }
            }
        }

        public void SetDetailBindingelements(string formid, string tag, string Selecteditem, string cName)
        {
            using (IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication())
            {
                XDocument Xdoc;
                IsolatedStorageFileStream stream;
                if (isoStore.FileExists("forms.xml"))
                {
                    stream = new IsolatedStorageFileStream("forms.xml", FileMode.Open, isoStore);
                    Xdoc = XDocument.Load(stream);
                    stream.Close();

                    var selectedform = from form in Xdoc.Descendants("form")
                                       where form.Element("id").Value == formid
                                       select form;
                    if (selectedform.Elements().Count() != 0)
                    {
                        XElement element = selectedform.ElementAt(0);
                        string layouttype = element.Element("detaillayout").Attribute("type").Value;

                        if (element.Element("detaillayout").Element(tag) != null)
                        {

                            element.Element("detaillayout").Element(tag).Element("bid").Value = Selecteditem;
                            element.Element("detaillayout").Element(tag).Element("name").Value = cName.ToString();
                        }
                        else
                        {
                            element.Element("detaillayout").Add(new XElement(tag,
                               new XElement("bid", Selecteditem),
                               new XElement("name", cName)));
                        }

                        stream = new IsolatedStorageFileStream("forms.xml", FileMode.Create, isoStore);
                        Xdoc.Save(stream);
                        stream.Close();
                    }
                }
            }
        }

        public string GetSelectedLayOutType(string formId)
        {
            string selecedlayouttype = "Simple";
            using (IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication())
            {
                IsolatedStorageFileStream isoStream;
                if (isoStore.FileExists("forms.xml"))
                {
                    isoStream = new IsolatedStorageFileStream("forms.xml", FileMode.Open, isoStore);
                    XElement formlayoutdoc = XElement.Load(isoStream);
                    isoStream.Close();

                    var selectedformlayout = from formlayout in formlayoutdoc.Descendants("form") where formlayout.Element("id").Value == formId select formlayout;
                    if (selectedformlayout.Elements("layout").Count() != 0)
                    {
                        foreach (XElement formlayout in selectedformlayout)
                        {
                            selecedlayouttype = formlayout.Element("layout").Attribute("type").Value;
                        }
                    }
                }
            }
            return selecedlayouttype;
        }

        public string GetSelectedDetailLayOutType(string formId)
        {
            //filepath = Path.Combine(AppPath, "App_Data\\forms.xml");
            string selecedDetaillayouttype = "Simple";

            using (IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication())
            {
                IsolatedStorageFileStream isoStream;
                if (isoStore.FileExists("forms.xml"))
                {
                    isoStream = new IsolatedStorageFileStream("forms.xml", FileMode.Open, isoStore);
                    XElement formlayoutdoc = XElement.Load(isoStream);
                    isoStream.Close();

                    var selectedformlayout = from formlayout in formlayoutdoc.Descendants("form") where formlayout.Element("id").Value == formId select formlayout;
                    if (selectedformlayout.Elements("detaillayout").Count() != 0)
                    {
                        foreach (XElement formlayout in selectedformlayout)
                        {
                            selecedDetaillayouttype = formlayout.Element("detaillayout").Attribute("type").Value;
                        }
                    }
                }
            }
            return selecedDetaillayouttype;
        }

        public ObservableCollection<XElement> LoadlayoutControls(string formid)
        {
            //filepath = Path.Combine(AppPath, "App_Data\\forms.xml");
            ObservableCollection<XElement> formlayoutcontrols = new ObservableCollection<XElement>();
            using (IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication())
            {
                IsolatedStorageFileStream stream;
                if (isoStore.FileExists("forms.xml"))
                {
                    stream = new IsolatedStorageFileStream("forms.xml", FileMode.Open, FileAccess.Read, isoStore);
                    if (stream.Length > 0)
                    {
                        XElement formlayoutdoc = XElement.Load(stream);
                        stream.Close();
                        var layoutcontrols = from formlayout in formlayoutdoc.Descendants("form") where formlayout.Element("id").Value == formid select formlayout;
                        formlayoutcontrols = layoutcontrols.ToObservableCollection();
                    }
                }
            }
            return formlayoutcontrols;
        }

        public ObservableCollection<XElement> GetSelectedFormItemDetails(string formid)
        {
            ObservableCollection<XElement> formelements = new ObservableCollection<XElement>();
            string filename = GetSelectedformName(formid) + ".xml";
            using (IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication())
            {
                IsolatedStorageFileStream stream;
                if (isoStore.FileExists(filename))
                {
                    stream = new IsolatedStorageFileStream(filename, FileMode.Open, FileAccess.Read, isoStore);
                    XElement formdetaildoc = XElement.Load(stream);
                    stream.Close();
                    var formdetails = (from fd in formdetaildoc.Elements("item") select fd);
                    formelements = formdetails.ToObservableCollection();
                }
            }
            return formelements;
        }

        public string GetSelectedformName(string formid)
        {
            string formname = string.Empty;
            using (IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication())
            {
                IsolatedStorageFileStream stream;
                if (isoStore.FileExists("forms.xml"))
                {
                    stream = new IsolatedStorageFileStream("forms.xml", FileMode.Open, FileAccess.Read, isoStore);
                    XElement formcontroldoc = XElement.Load(stream);
                    stream.Close();
                    var formdoc = (from f in formcontroldoc.Descendants("form") where f.Element("id").Value == formid select f);
                    foreach (XElement fm in formdoc)
                    {
                        formname = fm.Element("name").Value;
                    }
                }
            }
            return formname;
        }

        public string GetModufiedTemplate(string formId)
        {
            string xaml = string.Empty;
            using (IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication())
            {
                IsolatedStorageFileStream stream;
                if (isoStore.FileExists("formcontrols.xml"))
                {
                    stream = new IsolatedStorageFileStream("formcontrols.xml", FileMode.Open, isoStore);
                    XElement formcontrolsdoc = XElement.Load(stream);
                    stream.Close();
                    var template = from temp in formcontrolsdoc.Descendants("form") where temp.Attribute("id").Value == formId select temp;
                    foreach (var t in template)
                    {
                        if (t.Element("Template") != null)
                            xaml = t.Element("Template").Value.ToString();
                        else
                        {
                            xaml = "<DataTemplate><StackPanel Name='firststk' Orientation='Vertical'><TextBlock Text='{Binding P1}' TextWrapping='Wrap' /></StackPanel></DataTemplate>";
                        }
                    }

                    //ImageSource imgsrc = LoadFromLocalStorage("Img371.jpg", "Images") as ImageSource;

                    //xaml = xaml.Replace("{Binding Pdetailimage}", imgsrc.ToString());

                    xaml = xaml.Replace("<DataTemplate>", "<DataTemplate xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation'>");
                }
            }
            return xaml;
        }

        public object LoadFromLocalStorage(string imageFileName, string imageFolder)
        {
            object obj;
            var isoFile = IsolatedStorageFile.GetUserStoreForApplication();
            if (!isoFile.DirectoryExists(imageFolder))
            {
                isoFile.CreateDirectory(imageFolder);
            }

            string filePath = System.IO.Path.Combine(imageFolder, imageFileName);
            using (var imageStream = isoFile.OpenFile(filePath, FileMode.Open, FileAccess.Read))
            {
                var imageSource = PictureDecoder.DecodeJpeg(imageStream);
                //image.Source = imageSource;
                obj = imageSource as object;
            }
            return obj;
        }

        public void AddFormItemDetails(Dictionary<string, string> items, string formid)
        {
            string formname = GetSelectedformName(formid);
            string filename = formname + ".xml";
            using (IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication())
            {
                IsolatedStorageFileStream stream;
                if (!isoStore.FileExists(filename))
                {
                    XElement root = new XElement(formname);
                    XElement childele = new XElement("item", new XAttribute("id", 1));
                    foreach (var s in items)
                    {
                        XElement element = new XElement(s.Key);
                        element.Value = s.Value;
                        childele.Add(element);
                    }
                    root.Add(childele);

                    stream = new IsolatedStorageFileStream(filename, FileMode.Create, isoStore);
                    root.Save(stream);
                    stream.Close();
                }
                else
                {
                    stream = new IsolatedStorageFileStream(filename, FileMode.Open, isoStore);
                    XElement formdoc = XElement.Load(stream);
                    stream.Close();

                    int id = 0;
                    //obtain a Max formid from forms
                    IEnumerable<XElement> formdetails = (from fd in formdoc.Elements("item")
                                                         orderby (int)fd.Attribute("id") descending
                                                         select fd);

                    foreach (XElement xe in formdetails)
                    {
                        id = int.Parse(xe.Attribute("id").Value);
                        break;
                    }
                    id = id + 1;

                    //Adding new Record to forms
                    XElement newBook = new XElement("item", new XAttribute("id", id));
                    formdoc.Add(newBook);

                    foreach (var s in items)
                    {
                        XElement element = new XElement(s.Key);
                        element.Value = s.Value;
                        newBook.Add(element);
                    }

                    stream = new IsolatedStorageFileStream(filename, FileMode.Create, isoStore);
                    formdoc.Save(stream);
                    stream.Close();
                }
            }
        }

        //public void AddFormItemDetails1(List<DataDictionary> items, string formid)
        //{
        //    string formname = GetSelectedformName(formid);
        //    string filename = formname + ".xml";
        //    using (IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication())
        //    {
        //        IsolatedStorageFileStream stream;
        //        if (!isoStore.FileExists(filename))
        //        {
        //            XElement root = new XElement(formname);
        //            XElement childele = new XElement("item", new XAttribute("id", 1));
        //            foreach (var s in items)
        //            {
        //                XElement element = new XElement(s.Name);
        //                element.Value = s.Value;
        //                childele.Add(element);
        //            }
        //            root.Add(childele);

        //            stream = new IsolatedStorageFileStream(filename, FileMode.Create, isoStore);
        //            root.Save(stream);
        //            stream.Close();
        //        }
        //        else
        //        {
        //            stream = new IsolatedStorageFileStream(filename, FileMode.Open, isoStore);
        //            XElement formdoc = XElement.Load(stream);
        //            stream.Close();

        //            int id = 0;
        //            //obtain a Max formid from forms
        //            IEnumerable<XElement> formdetails = (from fd in formdoc.Elements("item")
        //                                                 orderby (int)fd.Attribute("id") descending
        //                                                 select fd);

        //            foreach (XElement xe in formdetails)
        //            {
        //                id = int.Parse(xe.Attribute("id").Value);
        //                break;
        //            }
        //            id = id + 1;

        //            //Adding new Record to forms
        //            XElement newBook = new XElement("item", new XAttribute("id", id));
        //            formdoc.Add(newBook);

        //            foreach (var s in items)
        //            {
        //                XElement element = new XElement(s.Name);
        //                element.Value = s.Value;
        //                newBook.Add(element);
        //            }

        //            stream = new IsolatedStorageFileStream(filename, FileMode.Create, isoStore);
        //            formdoc.Save(stream);
        //            stream.Close();
        //        }
        //    }
        //}

        public void SaveToCloud()
        {
            using (IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication())
            {
                string[] dirs = isoStore.GetFileNames("Images");
                string[] fileslist = isoStore.GetFileNames();
                foreach (string file in fileslist)
                {
                    IsolatedStorageFileStream stream;
                    if (isoStore.FileExists(file))
                    {

                        stream = new IsolatedStorageFileStream(file, FileMode.Open, FileAccess.Read, isoStore);
                        if (stream.Length > 0)
                        {
                            // Create a byte array of file stream length
                            byte[] ImageData = new byte[stream.Length];

                            //Read block of bytes from stream into the byte array
                            stream.Read(ImageData, 0, System.Convert.ToInt32(stream.Length));

                            //Close the File Stream
                            stream.Close();
                            client.SavefilestoCloudAsync(ImageData, file);
                            client.SavefilestoCloudCompleted += new EventHandler<AsyncCompletedEventArgs>(client_SavefilestoCloudCompleted);
                        }
                    }
                }

            }
        }

        void client_SavefilestoCloudCompleted(object sender, AsyncCompletedEventArgs e)
        {

        }


    }
}
